package com.ccsc.auth.cas.service;

import java.security.GeneralSecurityException;
import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.FailedLoginException;

import com.ccsc.auth.cas.entity.SysUserEntity;
import com.ccsc.auth.cas.entity.UserEntity;
import org.jasig.cas.authentication.HandlerResult;
import org.jasig.cas.authentication.PreventedException;
import org.jasig.cas.authentication.UsernamePasswordCredential;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.principal.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 密码登录验证
 * @create 2015-10-29 下午 15:28:24
 * @author xingwen
 */
@Component(value="primaryAuthenticationHandler")
public class UserAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;

	/**
	 * 方法重写
	 */
	@Override
	protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential) throws GeneralSecurityException, PreventedException {
		//UserEntity userEntity = null;
		SysUserEntity sysUserEntity = null;

		try {
			//userEntity = userService.verifyAccount(transformedCredential);
			sysUserEntity = userService.verifySysAccount(transformedCredential);
		}
		catch (Exception e)
		{
			logger.info("认证服务器异常！");
			throw new RuntimeException();
		}

		if(sysUserEntity != null){
			transformedCredential.setUserId(sysUserEntity.getUserId().toString());
			String username = sysUserEntity.getAccount();
			Boolean validAccessSystem = userService.validAccessSystem(username);
			if(validAccessSystem) {
				logger.info("用户：" + username + "登录成功！");
				Principal principal = this.principalFactory.createPrincipal(username);
				return createHandlerResult(transformedCredential, principal, null);
			}
			else {
				logger.info("无权限进入该系统！");
				throw new FailedLoginException();
			}
		}
		else {
			logger.info("用户名或密码错误！");
			throw new AccountNotFoundException();
		}
		//throw new FailedLoginException();
	}
}